package com.qnw.CardGroupManagement;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v4.util.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.view.animation.*;
import android.widget.*;
import android.widget.AdapterView.*;
import android.widget.TextView.*;
import com.qnw.CardGroupManagement.bean.*;
import com.qnw.CardGroupManagement.management.*;
import com.qnw.CardGroupManagement.util.*;
import com.ygo.feihua.*;
import com.ygo.feihua.adapter.*;
import com.ygo.feihua.util.*;
import java.io.*;
import java.util.*;

import android.support.v4.util.ArrayMap;
import android.view.View.OnClickListener;
import com.qnw.CardGroupManagement.adapter.*;
import com.qnw.CardGroupManagement.helper.*;

public class FragmentCDB extends Fragment implements OnItemClickListener,OnItemLongClickListener,OnClickListener
{

	private LinearLayout cdb_lin,cdb_batch;
	private ListView cdb_list_cdb,cdb_list_card;
	private EditText cdb_name;
	private TextView cdb_path,cdb_cxnumber,cdb_open,cdb_new;
	private Button cdb_cx;
	private View op_cdb,op_card;
	
	private AdapterCdb adpcb;
	private AdapterCardList adpc;
	
	private DialogUtils du;
	private CdbManagement cdbm;
	private Gongju gj;
	
	private String TAG="FragmentCdb";
	
	private List<Card> cardList=new ArrayList<Card>();
	
	G5 g5;
	
	int xz=2;
	private final static int TYPE_COMBINE_PATH=2;
	private final static int TYPE_CDB_PATH=0;
	private final static int TYPE_SAVE_CDB=3;
	private static final int TYPE_NEW_CDB = 4;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View v=inflater.inflate(R.layout.fragment_cdb,null);		
		initView(v);	
		// TODO: Implement this method
		return v;
	}


	@Override
	public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
	{
		switch(p1.getId()){
			case R.id.cdb_list_cdb:

				if(adpcb.isSelected()){
					String path1=(String)cdbm.getCdbList().get(p3).get("path");
					if(cdbm.getXzcdb().contains(path1)){
						cdbm.getXzcdb().remove(path1);
					}else{
						cdbm.getXzcdb().add(path1);
					}
					adpcb.notifyDataSetChanged();
				}else{
					openCdb(p3);
				}
				break;
			case R.id.cdb_list_card:
				String km=cardList.get(p3).getId();
				if(adpc.isSelected()){
					if(cdbm.conCard(km)){
						cdbm.removeCard(km);
					}else{
						Card c=new Card();
						c.setId(km);
						c.setName(cardList.get(p3).getName());
						cdbm.getXzcard().add(c);
					}
					adpc.notifyDataSetChanged();
				}else{
					g5.sxCard(km);
					g5.closeDrawer();
				}
				break;
		}

		// TODO: Implement this method
	}


	@Override
	public boolean onItemLongClick(AdapterView<?> p1, View p2, int p3, long p4)
	{
		switch(p1.getId()){
			case R.id.cdb_list_cdb:
				if(xz!=0&&xz!=1){
					if(!adpcb.isSelected()){
						cdbm.getXzcdb().add((String)cdbm.getCdbList().get(p3).get("path"));
						adpcb.setSelected(true);
					}
					cdb_lin.addView(op_cdb);
					op_cdb.startAnimation(AnimationUtils.loadAnimation(getActivity(),R.anim.in_from_down));
					xz=0;

				}
				break;
			case R.id.cdb_list_card:
				if(xz!=0&&xz!=1){
					if(!adpc.isSelected()){
						Card ca=new Card();
						ca.setId(cardList.get(p3).getId());
						ca.setName(cardList.get(p3).getName());
						cdbm.getXzcard().add(ca);
						adpc.setSelected(true);
					}
					cdb_lin.addView(op_card);
					op_card.startAnimation(AnimationUtils.loadAnimation(getActivity(),R.anim.in_from_down));

					xz=1;
				}
				break;
		}
		// TODO: Implement this method
		return true;
	}
	
	@Override
	public void onClick(View p1)
	{
		switch(p1.getId()){
			case R.id.cdb_open:
				startActivityForResult(new Intent(getActivity(),NewWjxz.class).putExtra("lx",NewWjxz.TYPE_CDB),TYPE_CDB_PATH);
				break;
			case R.id.cdb_new:
				gj.show("请选择数据库保存路径");
				startActivityForResult(new Intent(getActivity(),NewWjxz.class).putExtra("lx",NewWjxz.TYPE_PATH),TYPE_NEW_CDB);			
				break;
			case R.id.cdb_batch:
				cdbBatch();
				break;
			case R.id.card_batch:
				cardBatch();
				break;
			case R.id.card_copy:
				cardCopy();
				break;
			case R.id.card_move:
				cardMove();
				break;
			case R.id.card_del:
				cardDel();
				break;
			case R.id.cdb_saveas:
				if (cdbm.getXzcdb().size() != 1) {
					gj.show("一次只能另存为一个数据库");
				} else {
					gj.show("请选择路径");
					startActivityForResult(new Intent(getActivity(), NewWjxz.class).putExtra("lx", NewWjxz.TYPE_PATH), TYPE_SAVE_CDB);
				}
				break;
			case R.id.cdb_rename:
				cdbReName();		
				break;
			case R.id.cdb_del:
				cdbDel();
				break;
			case R.id.cdb_combine:
				cdbCombine();
				break;
			case R.id.cdb_cx:
				cardQuery();
				break;

		}
		// TODO: Implement this method
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO: Implement this method
		super.onActivityResult(requestCode, resultCode, data);
		switch(resultCode){
			case NewWjxz.TYPE_CDB:
				String path=data.getStringExtra("path");
				openCdb(path);
				break;
			case NewWjxz.TYPE_PATH:
				String path1=data.getStringExtra("path");

				switch(requestCode){			
					case TYPE_SAVE_CDB:
						try {
							FileUtil.copyFile(cdbm.getXzcdb().get(0), path1, false);
							gj.show("另存为成功");
						} catch (IOException e) {
							gj.show("另存为失败,原因为"+e);
						}

						setSelectedCDB(false);
						break;
					case TYPE_NEW_CDB:
						newCdb(path1);
						break;
				}

				break;	
		}
	}
	
	private void initView(View v)
	{
		cdb_list_card=(ListView) v.findViewById(R.id.cdb_list_card);
		cdb_list_cdb=(ListView) v.findViewById(R.id.cdb_list_cdb);
		cdb_cx=(Button) v.findViewById(R.id.cdb_cx);
		cdb_name=(EditText) v.findViewById(R.id.cdb_name);
		cdb_path=(TextView) v.findViewById(R.id.cdb_path);
		cdb_lin=(LinearLayout) v.findViewById(R.id.cdb_lin);
		cdb_cxnumber=(TextView) v.findViewById(R.id.cdb_cxnumber);
		cdb_open=(TextView) v.findViewById(R.id.cdb_open);
		cdb_new=(TextView) v.findViewById(R.id.cdb_new);

		gj=Gongju.getdx(getActivity());
		du=DialogUtils.getdx(getActivity());
		cdbm=CdbManagement.getdx();

		g5=(G5) getActivity();
		
		initOp();
		initCardList();
		initCdb();

		cdb_open.setOnClickListener(this);
		cdb_new.setOnClickListener(this);

		cdb_list_card.setOnItemClickListener(this);
		cdb_list_cdb.setOnItemClickListener(this);
		
		cdb_list_card.setOnItemLongClickListener(this);	
		cdb_list_cdb.setOnItemLongClickListener(this);

		cdb_name.setOnEditorActionListener(new OnEditorActionListener(){

				@Override
				public boolean onEditorAction(TextView p1, int p2, KeyEvent p3)
				{
					cardQuery();
					// TODO: Implement this method
					return true;
				}
			});

		cdb_cx.setOnClickListener(this);

		// TODO: Implement this method
	}

	
	
	private void initOp()
	{
		op_cdb=LayoutInflater.from(getActivity()).inflate(R.layout.operation_cdb,null);
		op_card=LayoutInflater.from(getActivity()).inflate(R.layout.operation_card,null);

		LinearLayout cdb_saveas,cdb_rename,cdb_del,cdb_combine;

		cdb_saveas=(LinearLayout) op_cdb.findViewById(R.id.cdb_saveas);
		cdb_rename=(LinearLayout) op_cdb.findViewById(R.id.cdb_rename);
		cdb_del=(LinearLayout) op_cdb.findViewById(R.id.cdb_del);
		cdb_combine=(LinearLayout) op_cdb.findViewById(R.id.cdb_combine);
		cdb_batch=(LinearLayout)op_cdb.findViewById(R.id.cdb_batch);

		cdb_batch.setOnClickListener(this);
		cdb_saveas.setOnClickListener(this);
		cdb_rename.setOnClickListener(this);
		cdb_del.setOnClickListener(this);
		cdb_combine.setOnClickListener(this);

		LinearLayout card_copy,card_move,card_del,card_batch;
		card_copy=(LinearLayout) op_card.findViewById(R.id.card_copy);
		card_move=(LinearLayout) op_card.findViewById(R.id.card_move);
		card_del=(LinearLayout) op_card.findViewById(R.id.card_del);
		card_batch=(LinearLayout) op_card.findViewById(R.id.card_batch);

		card_copy.setOnClickListener(this);
		card_move.setOnClickListener(this);
		card_del.setOnClickListener(this);
		card_batch.setOnClickListener(this);

		// TODO: Implement this method
	}

	private void initCardList()
	{
		adpc=new AdapterCardList(getActivity(),cardList);
		cdb_list_card.setAdapter(adpc);

		// TODO: Implement this method
	}

	private void initCdb()
	{
		adpcb=new AdapterCdb(getActivity(),cdbm.getCdbList());
		cdb_list_cdb.setAdapter(adpcb);
		if(cdbm.getCdbList().size()<1){
			openCdb(SharedPreferenceUtil.getCdbpath());

		}
		// TODO: Implement this method
	}
	
	private void cardQuery(){
		String name=cdb_name.getText().toString().trim();
		adpc.setData(Gongju.cardQuery(name,cdbm.getCdb()));
		cdb_cxnumber.setText(cardList.size()+"");
		adpc.notifyDataSetChanged();
		setSelectedCard(false);
		setSelectedCDB(false);
		gj.closeKeyboard();
	}
	

	public void openCdb(String path){
		Log.e(TAG,"打开数据库"+path);
		int f=-1;
		for(int i=0;i<cdbm.getCdbList().size();i++){
			if(((String)cdbm.getCdbList().get(i).get("path")).equals(path)){
				f=i;
			}
		}
		if(f!=-1){
			openCdb(f);
		}else{
			gj.show("已打开"+path);
			cdb_path.setText(path);
			Map<String,Object> map1=new ArrayMap<String,Object>();
			map1.put("name",new File(path).getName());
			map1.put("dq",true);
			map1.put("path",path);
			cdbm.getCdbList().add(cdbm.getCdbList().size(),map1);
			openCdb(cdbm.getCdbList().size()-1);
		}

	}


	//打开数据库
	private void openCdb(int position)
	{
		if(position!=cdbm.getDqcdb()){
			setSelectedCard(false);
			setSelectedCDB(false);

			adpcb.notifyDataSetChanged();
			cdbm.setDqcdb(position);	
			cdb_name.setText("");
			cardList.clear();
			cdb_cxnumber.setText("0");
			adpc.notifyDataSetChanged();
			if(position!=-1){
				cdb_path.setText((String)cdbm.getCdbList().get(position).get("path"));
				cdbm.setCdb((String)cdbm.getCdbList().get(position).get("path"));
			}else{
				cdb_path.setText("无打开数据库");
				g5.sxCard(null);
				closeCdb();
			}
		}
		// TODO: Implement this method
	}

	//关闭数据库
	private void closeCdb()
	{
		cdbm.closeCdb();
		// TODO: Implement this method
	}
	
	
	private void cdbBatch() {
		ListView llvv=(ListView) du.dialogl(true,"请选择要做的操作",new String[]{"导出卡组"});
		llvv.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, int position, long p4) {

					switch(position){
						case 0:
							View[] ve1=du.dialoge(false,"","请输入卡组名");
							final EditText ved1=(EditText) ve1[0];
							Button vbt1=(Button) ve1[1];
							vbt1.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View p1)
									{
										final String name=ved1.getText().toString().trim();
										if(name.equals("")){
											gj.show("卡组名不能为空");
										}else{
											du.dis();
											CgmaZhuye.getType();
											KzlistManagement kzm=KzlistManagement.getdx();
											final List<DeckType> da=kzm.getType();
											String ss[]=new String[da.size()-1];
											for(int i=0;i<ss.length;i++){
												ss[i]=da.get(i+1).getName();
											}

											ListView ll=(ListView) du.dialogl(true,"保存到",ss);
											ll.setOnItemClickListener(new OnItemClickListener(){

													@Override
													public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
													{
														du.dis();
														List<Card> lc=gj.cardQuery("");

														saveYdk(name, da.get(p3 + 1).getPath() , lc);

														setSelectedCDB(false);
														// TODO: Implement this method
													}
												});
										}
										// TODO: Implement this method
									}
								});
							break;
					}


					// TODO: Implement this method
				}
			});
		// TODO: Implement this method
	}

	private void cdbCombine() {
		if(cdbm.getXzcdb().size()>1){
			String[] ss=new String[cdbm.getXzcdb().size()+1];
			ss[0]="新建数据库";
			for(int i=0;i<cdbm.getXzcdb().size();i++){
				ss[i+1]=cdbm.getXzcdb().get(i);
			}
			ListView ll =(ListView) du.dialogl(true,"整合到",ss);
			ll.setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
					{
						if(p3==0){
							//	startActivityForResult(new Intent(getActivity(),NewWjxz.class).putExtra("lx",NewWjxz.TYPE_PATH),TYPE_COMBINE_PATH);
						}else{
							du.dis();
							combineCdb(p3);

						}
						// TODO: Implement this method
					}
				});
		}else{
			gj.show("至少选择两个数据库");
		}
		// TODO: Implement this method
	}

	public void saveYdk(final String deckName,final String savePath,final List<Card> cardList) {
		View[] v=du.dialogj1(false,"导出卡组中","正在导出");
		TextView tv=(TextView) v[0];

		int cardNum=cardList.size();
		final int deckNum;//,mainNum,exNum;
		if(cardNum%90==0){
			deckNum=cardNum/90;
		}else{
			deckNum=cardNum/90+1;
		}
		tv.setText("准备导出卡组数量:"+deckNum);
		new Thread(new Runnable(){

				@Override
				public void run(){
					String dm = null;
					int no=0;
					for (int n=0;n < deckNum;n++) {
						Message me=new Message();
						me.obj=new int[]{deckNum,n};
						me.what=6;
						han.sendMessage(me);
						String deck="#main";
						for (int i=0;i < 90;i++) {

							if (i == 60) {
								deck += "\n!extra" + "\n" + cardList.get(i).getId();
							} else if (i == 75) {
								deck += "\n!side" + "\n" + cardList.get(i).getId();
							} else {
								deck += "\n" + cardList.get(i).getId();
							}
						}
						if(n!=0){
							dm=deckName+n;
						}

						try {
							FileOutputStream fos=new FileOutputStream(savePath+dm+".ydk");
							fos.write(deck.getBytes());
							fos.close();

						} catch (IOException e) {
							no++;
						}

					}
					Message me=new Message();
					me.obj=new int[]{deckNum,no};
					me.what=7;
					han.sendMessage(me);
					// TODO: Implement this method
				}
			}).start();

		// TODO: Implement this method
	}

	private void cdbDel() {
		if(cdbm.getXzcdb().size()==0){	
			gj.show("至少选择一个数据库");
		}else{
			String ds="";
			for(String ss:cdbm.getXzcdb()){
				ds+=ss+"\n";
			}
			View[] vv=du.dialogt(false,"",ds+"确定删除这些数据库?");
			Button b1,b2;
			b1=(Button) vv[0];
			b2=(Button) vv[1];
			b1.setText("取消");
			b2.setText("删除");
			b1.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View p1)
					{
						du.dis();
						setSelectedCDB(false);
						// TODO: Implement this method
					}
				});
			b2.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View p1)
					{

						//获取当前数据库路径
						String path=(String)cdbm.getCdbList().get(cdbm.getDqcdb()).get("path");
						//删除失败的个数
						int a=0;
						//当前数据库是否被删除
						boolean b=false;
						//如果
						for(String ss:cdbm.getXzcdb()){
							if(ss.equals(path)){
								b=true;
								closeCdb();
							}
							//如果删除成功
							if(FileUtil.delFile(ss)){

								for(int i=0;i<cdbm.getCdbList().size();i++){
									if(ss.equals((String)cdbm.getCdbList().get(i).get("path"))){
										cdbm.getCdbList().remove(i);
									}
								}
							}else{
								a++;
							}
						}
						du.dis();

						if(cdbm.getCdbList().size()!=1){ 
							if(b){ 
								//如果当前cdb被删除
								Map<String,Object> map=cdbm.getCdbList().get(0);
								map.put("dq",true);
								cdbm.getCdbList().set(0,map);
								openCdb(0);
							}
						}else{
							//如果列表中所有的cdb都被删除
							openCdb(-1);
						}
						adpcb.notifyDataSetChanged();
						if(a==0){
							gj.show("删除完成");
						}else{
							gj.show("删除完成,成功删除"+(cdbm.getXzcdb().size()-a)+"个,删除失败"+a+"个");
						}

						setSelectedCDB(false);
						// TODO: Implement this method
					}
				});
		}
		// TODO: Implement this method
	}

	private void cdbReName() {
		if(cdbm.getXzcdb().size()!=1){
			gj.show("一次只能重命名一个数据库");
		}else{
			View[] vv=du.dialoge(false,"","请输入数据库名称");
			final EditText et=(EditText) vv[0];
			String cdbna=new File(cdbm.getXzcdb().get(0)).getName();
			et.setText(cdbna);
			Button bt=(Button) vv[1];
			bt.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View p1)
					{
						String cm=et.getText().toString().trim();
						String oldpath=cdbm.getXzcdb().get(0);
						if(!cm.equals( oldpath)){
							if(FileUtil.cmm(oldpath,cm)){
								gj.show("重命名成功");
								du.dis();

								for(int i=0;i<cdbm.getCdbList().size();i++){
									if(oldpath.equals((String)cdbm.getCdbList().get(i).get("path"))){
										Map<String,Object> ma=cdbm.getCdbList().get(i);
										ma.put("path",new File(oldpath).getParent()+"/"+cm);
										ma.put("name",cm);
										cdbm.getCdbList().set(i,ma);
									}
								}
								adpcb.notifyDataSetChanged();

							}else{
								gj.show("重命名失败");
							}
							setSelectedCDB(false);
						}
						// TODO: Implement this method
					}
				});
		}
		// TODO: Implement this method
	}

	private void cardDel() {
		if(cdbm.getXzcard().size()==0){	
			gj.show("至少选择一张卡");
		}else{
			View[] vv=du.dialogt(false,"","确定删除卡片?");
			Button b1,b2;
			b1=(Button) vv[0];
			b2=(Button) vv[1];
			b1.setText("取消");
			b2.setText("删除");
			b1.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View p1)
					{
						du.dis();
						setSelectedCard(false);
						// TODO: Implement this method
					}
				});
			b2.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View p1)
					{

						if(cdbm.getXzcard().size()<2){
							for(Card ca:cdbm.getXzcard()){
								cdbm.getCdb().delete("datas","id LIKE?", new String[]{"%" + ca.getId()});
								cdbm.getCdb().delete("texts","id LIKE?", new String[]{"%" + ca.getId()});

								removeCard(ca.getId());
							}
							du.dis();
							adpc.notifyDataSetChanged();
							gj.show("删除成功");

							setSelectedCard(false);

						}else{
							du.dis();
							du.dialogj1(false,"","删除中,请稍等");
							new Thread(new Runnable(){

									@Override
									public void run()
									{
										for(Card ca:cdbm.getXzcard()){
											cdbm.getCdb().delete("datas","id LIKE?", new String[]{"%" + ca.getId()});
											cdbm.getCdb().delete("texts","id LIKE?", new String[]{"%" + ca.getId()});

											removeCard(ca.getId());
										}
										Message me=new Message();
										me.what=2;
										han.sendMessage(me);
										// TODO: Implement this method
									}
								}).start();
						}
					}});
		}
		// TODO: Implement this method
	}

	private void cardMove() {
		if(cdbm.getXzcard().size()>0){

			List<String> lls=new ArrayList<String>();
			lls.add("新建数据库");
			for(int i=0;i<cdbm.getCdbList().size();i++){				
				String path=(String)cdbm.getCdbList().get(i).get("path");
				if(path!=null&&!path.equals("")&&!path.equals((String)cdbm.getCdbList().get(cdbm.getDqcdb()).get("path"))){
					lls.add(path);

				}

			}
			final String[] ss=new String[lls.size()];
			for(int i=0;i<lls.size();i++){
				ss[i]=lls.get(i);

			}

			ListView ll =(ListView) du.dialogl(true,"移动到",ss);
			ll.setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
					{
						if(p3==0){
							//	startActivityForResult(new Intent(getActivity(),NewWjxz.class).putExtra("lx",NewWjxz.TYPE_PATH),TYPE_COMBINE_PATH);
						}else{
							du.dis();
							CopyCdb(true,(String)cdbm.getCdbList().get(cdbm.getDqcdb()).get("path"),ss[p3]);
						}
						// TODO: Implement this method
					}					
				});
		}else{
			gj.show("至少选择一张卡");
		}
		// TODO: Implement this method
	}

	private void cardCopy() {

		if(cdbm.getXzcard().size()>0){

			List<String> lls=new ArrayList<String>();
			lls.add("新建数据库");
			for(int i=0;i<cdbm.getCdbList().size();i++){				
				String path=(String)cdbm.getCdbList().get(i).get("path");
				if(path!=null&&!path.equals("")&&!path.equals((String)cdbm.getCdbList().get(cdbm.getDqcdb()).get("path"))){
					lls.add(path);
				}
			}
			final String[] ss=new String[lls.size()];
			for(int i=0;i<lls.size();i++){
				ss[i]=lls.get(i);

			}

			ListView ll =(ListView) du.dialogl(true,"复制到",ss);
			ll.setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
					{
						if(p3==0){
							//	startActivityForResult(new Intent(getActivity(),NewWjxz.class).putExtra("lx",NewWjxz.TYPE_PATH),TYPE_COMBINE_PATH);
						}else{
							du.dis();
							CopyCdb(false,(String)cdbm.getCdbList().get(cdbm.getDqcdb()).get("path"),ss[p3]);
						}
						// TODO: Implement this method
					}					
				});
		}else{
			gj.show("至少选择一张卡");
		}
		// TODO: Implement this method
	}

	private void cardBatch() {
		ListView llv=(ListView) du.dialogl(true,"请选择要做的操作",new String[]{"修改归属","修改字段","导出卡组","添加效果文本"});
		llv.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
				{
					du.dis();
					switch(p3){
						case 0:
							List<String> ls=new ArrayList<String>();
							for(String s:CardMessage.CARD_OT){
								ls.add(s);
							}
							DialogUtils.Select se= du.dialogRadio("请选择归属",ls,0);
							se.setOnRadioListener(new DialogUtils.OnRadioListener(){

									@Override
									public void onRadio(List<String> data, int position)
									{

										final String ss=CardMessage.CARD_OT_16[position];

										du.dis();
										du.dialogj1(false,"","合并中");
										
										new Thread(new Runnable(){

												@Override
												public void run()
												{

													int cc=cdbm.getXzcard().size();
													for(int i=0;i<cc;i++){
														Card c=cdbm.getXzcard().get(i);

														Message me=new Message();
														me.what = 0;
														me.obj = "修改中" + (i+1) + "/" + (cc);
														han.sendMessage(me);
														ContentValues cv=new ContentValues();
														cv.put("ot",ss);
														cdbm.getCdb().update("datas",cv,"id=?",new String[]{c.getId()});
													}
													han.sendEmptyMessage(5);
													// TODO: Implement this method
												}
											}).start();


										// TODO: Implement this method
									}
								});
							break;
						case 1:

							View[] vi=du.dialogzd(true,"卡片字段");
							final EditText sjk_ezd1,sjk_ezd2,sjk_ezd3,sjk_ezd4;
							sjk_ezd1=(EditText) vi[0];
							sjk_ezd2=(EditText) vi[1];
							sjk_ezd3=(EditText) vi[2];
							sjk_ezd4=(EditText) vi[3];
							Button qd=(Button) vi[4];



							qd.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View p1)
									{
										String zd1,zd2,zd3,zd4;

										zd1=sjk_ezd1.getText().toString().trim();
										zd2=sjk_ezd2.getText().toString().trim();
										zd3=sjk_ezd3.getText().toString().trim();
										zd4=sjk_ezd4.getText().toString().trim();

										String zd="";	
										if (!zd1.equals("")){
											int ii=zd1.length();
											for (int i=0;i < 4 - ii;i++){
												zd1 = "0" + zd1;
											}
											zd = zd1;
										}

										if (!zd2.equals("")){
											int ii=zd2.length();
											for (int i=0;i < 4 - ii;i++){
												zd2 = "0" + zd2;
											}
											zd= zd+ zd2;
										}

										if (!zd3.equals("")){
											int ii=zd3.length();
											for (int i=0;i < 4 - ii;i++){
												zd3 = "0" + zd3;
											}
											zd = zd + zd3;
										}

										if (!zd4.equals("")){
											int ii=zd4.length();
											for (int i=0;i < 4 - ii;i++){
												zd4 = "0" + zd4;
											}
											zd = zd + zd4;
										}
										if(zd.trim().equals("")){
											zd="0";
										}
										du.dis();
										du.dialogj1(false,"","合并中");
										
										final String zdd=zd;
										new Thread(new Runnable(){

												@Override
												public void run()
												{
													int cc=cdbm.getXzcard().size();
													for(int i=0;i<cc;i++){
														Card c=cdbm.getXzcard().get(i);

														Message me=new Message();
														me.what = 0;
														me.obj = "修改中" + (i+1) + "/" + (cc);
														han.sendMessage(me);

														ContentValues cv=new ContentValues();
														cv.put("setcode", Integer.valueOf(zdd, 16).toString());
														cdbm.getCdb().update("datas",cv,"id=?",new String[]{c.getId()});
													}
													han.sendEmptyMessage(5);
													// TODO: Implement this method
												}
											}).start();


										// TODO: Implement this method
									}
								});
							break;
						case 2:

							View[] ve1=du.dialoge(false,"","请输入卡组名");
							final EditText ved1=(EditText) ve1[0];
							Button vbt1=(Button) ve1[1];
							vbt1.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View p1)
									{
										final String name=ved1.getText().toString().trim();
										if(name.equals("")){
											gj.show("卡组名不能为空");
										}else{
											du.dis();
											CgmaZhuye.getType();
											KzlistManagement kzm=KzlistManagement.getdx();
											final List<DeckType> da=kzm.getType();
											String ss[]=new String[da.size()-1];
											for(int i=0;i<ss.length;i++){
												ss[i]=da.get(i+1).getName();
											}

											ListView ll=(ListView) du.dialogl(true,"保存到",ss);
											ll.setOnItemClickListener(new OnItemClickListener(){

													@Override
													public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
													{
														du.dis();
														saveYdk(name, da.get(p3 + 1).getPath(), cdbm.getXzcard());
														setSelectedCard(false);

														// TODO: Implement this method
													}
												});
										}
										// TODO: Implement this method
									}
								});



							break;
						case 3:
							addCardDescText();
							break;
					}

					// TODO: Implement this method
				}


			});
		// TODO: Implement this method
	}

	private void addCardDescText() {
		View[] v=du.dialoge(true,"添加效果文本","输入内容将添加至卡片效果末尾");
		final EditText et=(EditText) v[0];
		Button bt=(Button) v[1];
		bt.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1) {
					final String message=et.getText().toString().trim();

					if(message.equals("")){
						gj.show("内容不能为空");
					}else{
						du.dialogj1(true,"添加效果文本","修改中喵~");
						new Thread(new Runnable(){

								@Override
								public void run()
								{
									int cc=cdbm.getXzcard().size();
									for(int i=0;i<cc;i++){
										Card c=cdbm.getXzcard().get(i);

										Message me=new Message();
										me.what = 0;
										me.obj = "修改中" + (i+1) + "/" + (cc);
										han.sendMessage(me);
										
										cdbm.getCdb().execSQL("update texts set desc = desc||"+message+" where id="+c.getId());
									}
									han.sendEmptyMessage(5);
									// TODO: Implement this method
								}
							}).start();
					}

					// TODO: Implement this method
				}
			});


		// TODO: Implement this method
	}

	private void newCdb(final String savePath) {
		ListView lv=(ListView) du.dialogl(true,"请选择新建数据库类型",new String[]{"新建空白数据库","读取NW卡片数据生成数据库"});
		lv.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, final int position, long p4) {
					du.dis();

					View[] ve1=du.dialoge(false,"","请输入数据库名");
					final EditText ved1=(EditText) ve1[0];
					Button vbt1=(Button) ve1[1];
					vbt1.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{
								final String name=ved1.getText().toString().trim();
								if(name.equals("")){
									gj.show("数据库名不能为空");
								}else{
									du.dis();
									SQLiteDatabase sd = new CardCdbHelper(getActivity(),savePath,name+".cdb").getWritableDatabase();
									switch(position){
										case 0:
											openCdb(savePath+name+".cdb");
											break;
										case 1:
											jsonNw(sd);
											break;
									}
								}
							}
						});	


					// TODO: Implement this method
				}
			});
		// TODO: Implement this method
	}

	Handler han=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			// TODO: Implement this method
			super.handleMessage(msg);
			switch(msg.what){
				case 0:
					du.setToast((String)msg.obj);
					break;
				case 1:
					gj.show("合并完成");
					du.dis();
					setSelectedCDB(false);
					break;
				case 2:
					du.dis();
					adpc.notifyDataSetChanged();
					gj.show("删除成功");
					setSelectedCard(false);
					break;
				case 3:
					gj.show("复制成功");
					du.dis();
					setSelectedCDB(false);
					break;
				case 4:
					gj.show("复制成功");
					du.dis();
					setSelectedCDB(false);
					adpc.notifyDataSetChanged();
					break;
				case 5:
					du.dis();
					gj.show("修改完成");
					setSelectedCard(false);
					break;
				case 6:
					du.setToast("正在导出卡组"+((int[])msg.obj)[1]+"/"+((int[])msg.obj)[0]);
					break;
				case 7:
					du.dis();
					int[] ii=(int[]) msg.obj;
					Button bt=(Button) du.dialogt1(true,"导出完毕","应导出卡组:"
												   +ii[0]+"\n实际导出卡组:"+(ii[0]-ii[1])+"\n导出失败:"+ii[1])[0];
					bt.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1) {
								du.dis();
								// TODO: Implement this method
							}
						});
					break;
			}
		}



	};

	private void removeCard(String km){
		for( int i=0;i<cardList.size();i++) {
			Card map=cardList.get(i);
			if((map.getId()).equals(km)){
				cardList.remove(map);
				break;
			}
		}	
	}
	private void CopyCdb(final boolean del,final String oldPath,final String newPath)
	{
		final String ts;
		if(del){
			ts="移动中";
		}else{
			ts="复制中";
		}
		du.dialogj1(false,"",ts);
		
		new Thread(new Runnable(){

				@Override
				public void run()
				{
					List<Card> ls=cdbm.getXzcard();
					SQLiteDatabase main= SQLiteDatabase.openOrCreateDatabase(oldPath,null);
					SQLiteDatabase sq=SQLiteDatabase.openOrCreateDatabase(newPath,null);

					for (int f=0;f < ls.size();f++)
					{
						String id=ls.get(f).getId();
						Message me=new Message();
						me.what = 0;
						me.obj = ts + (f+1 ) + "/" + (ls.size());
						han.sendMessage(me);

						Cursor sq1=sq.query("texts", CardMessage.CDB_TEXTS, "id LIKE?", new String[]{"%" + id}, null, null, null);
						if(sq1.getCount()==0){
							Cursor texts=main.query("texts", CardMessage.CDB_TEXTS, "id LIKE?", new String[]{"%" + id}, null, null, null);
							Cursor datas=main.query("datas", CardMessage.CDB_DATAS, "id LIKE?", new String[]{"%" + id}, null, null, null);

							if(texts.getCount()!=0&&datas.getCount()!=0){
								texts.moveToNext();
								datas.moveToNext();
								ContentValues c=new ContentValues();
								ContentValues c1=new ContentValues();
								for (int i=0;i < CardMessage.CDB_DATAS.length;i++)
								{
									c.put(CardMessage.CDB_DATAS[i], datas.getString(i));
								}
								for (int i=0;i < CardMessage.CDB_TEXTS.length;i++)
								{
									String ff=texts.getString(i);
									c1.put(CardMessage.CDB_TEXTS[i], ff);
								}
								sq.insert("datas", null, c);
								sq.insert("texts", null, c1);
								if(del){
									main.delete("texts","id LIKE?", new String[]{"%" + id});
									removeCard(id);
								}
							}
						}
					}
					sq.close();
					Message me1=new Message();
					if(del){
						me1.what=4;
					}else{
						me1.what = 3;
					}
					han.sendMessage(me1);

					// TODO: Implement this method
				}
			}).start();

		// TODO: Implement this method
	}

	private void combineCdb(final int p3)
	{
		cdb_name.setText("");
		cardList.clear();
		adpc.notifyDataSetChanged();

		du.dialogj1(false,"","合并中");
	
		new Thread(new Runnable(){

				@Override
				public void run()
				{
					List<String> ls=cdbm.getXzcdb();
					SQLiteDatabase main= SQLiteDatabase.openOrCreateDatabase(ls.get(p3-1), null);
					ls.remove(ls.get(p3 - 1));
					SQLiteDatabase sq;

					for (int f=0;f < ls.size();f++)
					{

						String ss=ls.get(f);
						Message me=new Message();
						me.what = 0;
						me.obj = "合并中" + (f + 2) + "/" + (ls.size() + 1);
						han.sendMessage(me);

						sq = SQLiteDatabase.openOrCreateDatabase(ss, null);

						int cc=0;
						//查询全部数据
						Cursor cu = sq.rawQuery("SELECT * FROM texts", null);
						int cum=cu.getCount();
						if (cum != 0)
						{
							while (cu.moveToNext())
							{
								cc++;
								Message me2=new Message();
								me2.what = 0;
								me2.obj = "合并中" + (f + 2) + "/" + (ls.size() + 1)+"\n"+cc+"/"+cum;
								han.sendMessage(me2);

								String id=cu.getString(0);

								Cursor texts=main.query("texts", CardMessage.CDB_TEXTS, "id LIKE?", new String[]{"%" + id}, null, null, null);
								if (texts.getCount() == 0)
								{
									Cursor datas=sq.query("datas", CardMessage.CDB_DATAS, "id LIKE?", new String[]{"%" + id}, null, null, null);

									if (datas.getCount() != 0)
									{
										datas.moveToNext();
										ContentValues c=new ContentValues();
										ContentValues c1=new ContentValues();
										for (int i=0;i < CardMessage.CDB_DATAS.length;i++)
										{
											c.put(CardMessage.CDB_DATAS[i], datas.getString(i));
										}
										for (int i=0;i < CardMessage.CDB_TEXTS.length;i++)
										{
											String ff=cu.getString(i);
											c1.put(CardMessage.CDB_TEXTS[i], ff);
										}
										main.insert("datas", null, c);
										main.insert("texts", null, c1);

									}
								}
							}
						}
						sq.close();
					}

					cdbm.setCdb(main);
					Message me1=new Message();
					me1.what = 1;
					han.sendMessage(me1);

					// TODO: Implement this method
				}
			}).start();

		// TODO: Implement this method
	}
	
	
	
	public boolean isSelectedCard(){
		return adpc.isSelected();
	}
	
	public void setSelectedCard(boolean b){

		if(!b){
			op_card.startAnimation(AnimationUtils.loadAnimation(getActivity(),R.anim.out_from_top));
			cdb_lin.removeView(op_card);
			xz=3;
		}
		adpc.setSelected(b);
		
	}
	
	public boolean isSelectedCDB(){
		return adpcb.isSelected();
	}
	
	public void setSelectedCDB(boolean b){

		if(!b){
			op_cdb.startAnimation(AnimationUtils.loadAnimation(getActivity(),R.anim.out_from_top));
			cdb_lin.removeView(op_cdb);
			xz=3;
		}
		adpcb.setSelected(b);
	}
	
	public void jsonNw(final SQLiteDatabase sd) {

		final View[] v=du.dialoge(true,"卡包名称","解析的卡包名称,如CIBR");
		
		((Button)v[1]).setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1) {
					final String packageName=((EditText)v[0]).getText().toString().trim();
					if(packageName.equals("")){
						gj.show("卡包名不能为空");
					}else{
						du.dis();
						final View[] v1=du.dialoge(true,"卡密前缀","请输入卡密前缀");
						
						((Button)v1[1]).setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View p1) {
									 final String lastId=((EditText)v1[0]).getText().toString().trim();
									if(lastId.equals("")){
										gj.show("卡密前缀不能为空");
									}else{
										du.dis();
										final View[] v2=du.dialoge(true,"解析内容","请输入Nw卡片信息");
										
										((Button)v2[1]).setOnClickListener(new OnClickListener(){

												@Override
												public void onClick(View p1) {
													String jsonMessage=((EditText)v2[0]).getText().toString().trim();	
													if(jsonMessage.equals("")){
														gj.show("Nw卡片信息不能为空");
													}else{
														du.dis();
														List<Card> lc= jsonNw(lastId,packageName,jsonMessage);
														for(Card card:lc){
															
															ContentValues c=new ContentValues();//用来包装数
															c.put("id", card.getId());
															c.put("race", card.getRace_16());//将要插入的值
															c.put("attribute", card.getAttribute_16());
															c.put("level",card.getLevel_16());
															c.put("type", card.getCard_type_16());
															c.put("atk", card.getAtk_16());
															c.put("def", card.getDef_16());
															c.put("ot", card.getOt_16());
															c.put("category", card.getEffect_type_16());
															c.put("setcode", card.getSetcode_16());
													
															c.put("alias",card.getAlias());
														
															ContentValues c1=new ContentValues();
															c1.put("id", card.getId());
															c1.put("name", card.getName());
															c1.put("desc", card.getDesc());
															for (int i=0;i < card.getStr().size();i++) {
																c1.put("str" + Integer.toString(i + 1), card.getStr().get(i));														
															}

															sd.insert("datas", null, c);
															sd.insert("texts", null, c1);
																							
														}
														gj.show("新建成功");

														
													}
													// TODO: Implement this method
												}
											});
												
									}
									
									// TODO: Implement this method
								}
							});							
					}				
					// TODO: Implement this method
				}
			});
		// TODO: Implement this method
	}
	
	
	
	public static List<Card> jsonNw(String lastId,String packageName,String cardMessage){

		List<Card> lc=new ArrayList<Card>();
		int bh=100;
		for(String s:cardMessage.split(packageName)){
			if(!s.trim().equals("")){
				int a=s.indexOf("※");
				if(a!=-1){
					s=s.substring(0,a);
				}

				s=packageName+s.trim();
				int st1=s.indexOf("\n");
				String head=s.substring(0,st1).trim();
				String desc=s.substring(st1,s.length()).trim();
				int nameStart=head.lastIndexOf("(");
				int nameEnd=head.lastIndexOf(")");
				String panu=packageName+"-JP";
				int numberStart=head.indexOf(panu);
				
				String name=head.substring(nameStart+1,nameEnd).trim();
				String lastMessage=head.substring(nameEnd+1,head.length()).trim();
				int ms=lastMessage.indexOf("魔法");
				int xs=lastMessage.indexOf("陷阱");
				Card card=new Card();
				card.setDesc(desc);
				card.setName(name);
				card.setOt_16("1");//ocg
				card.setEffect_type_16(0);
				card.setSetcode_16(0);
				card.setAlias("0");
				if(numberStart!=-1){
					String number=head.substring(numberStart+panu.length(),numberStart+panu.length()+3);
					card.setId(lastId+number);
				}else{
					card.setId(lastId+bh);
					bh++;
				}
				
				for(int i=0;i<16;i++){
					card.addStr("");
				}
				
				if(ms!=-1&&ms==lastMessage.length()-2){
					String type=lastMessage.substring(0,ms);
					card.setAttribute_16("0");
					card.setRace_16("0");
					card.setLevel_16(0,"0");
					card.setAtk("0");
					card.setDef("0");
					int result1 = 0;
					for (int i=0;i < CardMessage.CARD_TYPE.length;i++) {
						String si=CardMessage.CARD_TYPE[i];
						if (type.indexOf(si) != -1) {
							result1 += Integer.valueOf(CardMessage.CARD_TYPE_16[i], 16);
						}
					}
					card.setCard_type_16(result1);
					
				}else if(xs!=-1){
					String type=lastMessage.substring(0,xs);
					card.setAttribute_16("0");
					card.setRace_16("0");
					card.setLevel_16(0,"0");
					card.setAtk("0");
					card.setDef("0");
					int result1 = 0;
					for (int i=0;i < CardMessage.CARD_TYPE.length;i++) {
						String si=CardMessage.CARD_TYPE[i];
						if (type.indexOf(si) != -1) {
							result1 += Integer.valueOf(CardMessage.CARD_TYPE_16[i], 16);
						}
					}
					card.setCard_type_16(result1);
				}else{
					String[] ss=lastMessage.split(" ");
					card.setAttribute(ss[0]);
					String race;
					
					if(lastMessage.indexOf("星")!=-1){		
					card.setLevel(ss[1].substring(0,ss[1].length()-1));
					card.setAtk(ss[3]);
					card.setDef(ss[4]);
						race=ss[2];
						
					}else{
						//连接怪兽
						race=ss[1];
						card.setAtk(ss[2]);
						card.setLevel(ss[3]);
						String link=ss[4];
						card.setDef(CardMessage.getLink_16(link));
					}
					int end=race.indexOf("/");
					if(end!=-1){
						race=race.substring(0,end);
					}
					card.setRace(race);
				}
				lc.add(card);
			}
		
	}
	return lc;
	}
}
